import { MMKV } from 'react-native-mmkv';

import { APP_NAME } from '@/constants';

// 使用一个实例，ID作为标识
export const storage = new MMKV({
  id: `${APP_NAME}_app_storage`,
});

// 设置storage，注意，对象和数组需要JSON.stringify()序列化
// 注意设置的时候可以设置string\number\boolean等类型,但是获取的时候需要区分
export const setStorageItem = (key: string, value: string | number | boolean | Uint8Array) => {
  storage.set(key, value);
};

// 获取storage，字符串类型注意，对象和数组需要JSON.parse()反序列化
export const getStorageItem = (key: string) => {
  return storage.getString(key);
};

export const getStorageBooleanItem = (key: string) => {
  return storage.getBoolean(key);
};

// 获取storage,number类型
export const getStorageNumberItem = (key: string) => {
  return storage.getNumber(key);
};

// 获取storage所有key
export const getStorageAllKeys = () => {
  return storage.getAllKeys();
};

// 删除storage
export const removeStorageItem = (key: string) => {
  storage.delete(key);
};

// 清空storage
export const clearStorageAllItems = () => {
  storage.clearAll();
};

export const localStorage = {
  storage,
  setStorageItem,
  getStorageItem,
  getStorageNumberItem,
  getStorageAllKeys,
  removeStorageItem,
  clearStorageAllItems,
  /**
   * 查询数组
   * @param key key
   */
  getStorageArrayItem<T>(key: string) {
    const existingValue = getStorageItem(key);
    const array: T[] = existingValue ? JSON.parse(existingValue) : null;
    if (!Array.isArray(array)) {
      // console.warn('Value is not an array');
      return null;
    }
    return array;
  },
  /**
   * 追加数组
   * @param key key
   * @param newValue 新值
   */
  appendStorageArrayItem(key: string, newValue: unknown) {
    const existingValue = getStorageItem(key);
    const array = existingValue ? JSON.parse(existingValue) : [];
    if (!Array.isArray(array)) {
      console.warn('Value is not an array');
      return null;
    }
    array.push(newValue);
    return storage.set(key, JSON.stringify(array));
  },
  /**
   * 删除数组
   * @param key key
   * @param filter 过滤器 (Array.filter)
   */
  removeStorageArrayItem<T>(key: string, filter: (item: T) => boolean) {
    console.log('====================================');
    console.log('removeStorageArrayItem', key, filter);
    console.log('====================================');
    const existingValue = getStorageItem(key);
    let array = existingValue ? JSON.parse(existingValue) : [];
    if (!Array.isArray(array)) {
      console.warn('Value is not an array');
      return null;
    }
    array = array.filter(filter);
    console.log('====================================');
    console.log('array', array);
    console.log('====================================');
    return storage.set(key, JSON.stringify(array));
  },
};
